﻿namespace PillBox.Client.Views
{
    using System;
    using System.Windows.Controls;
    using Microsoft.Phone.Controls;
    using PillBox.Client.Framework;

    public partial class HomeView : PhoneApplicationPage, IView
    {
        private bool _animateOutCompleted;
        private Action _completedAction;

        public HomeView()
        {
            InitializeComponent();
        }

        public void DeActivate(Action completed)
        {
            System.Diagnostics.Debug.WriteLine("HomeView().DeActivate()");

            this._completedAction = completed;

            this.AnimateOut.Completed += AnimateOut_Completed;
            this.AnimateOut.Begin();

            if (this.Tag != null)
            {
                ContentControl contentControl = this.FindName(this.Tag.ToString()) as ContentControl;

                IView view = contentControl.Content as IView;

                if (view != null)
                {
                    view.DeActivate(this.RaiseCompleted);
                }
                else
                {
                    RaiseCompleted();
                }
            }
            else
            {
                RaiseCompleted();
            }
        }

        private void AnimateOut_Completed(object sender, EventArgs e)
        {
            this._animateOutCompleted = true;
            RaiseCompleted();
        }

        private void RaiseCompleted()
        {
            if (this._animateOutCompleted && this._completedAction != null)
            {
                this._completedAction();
                this._completedAction = null;
            }
        }
    }
}